//
//  HDCustomComponent.m
//  HDecoration
//
//  Created by koki on 15-4-24.
//  Copyright (c) 2015年 HDecoration. All rights reserved.
//

#import "HDCustomComponent.h"


@implementation NSObject (PerformBlockAfterDelay)

- (void)performBlock:(void (^)(void))block
          afterDelay:(NSTimeInterval)delay
{
    [self performSelector:@selector(fireBlockAfterDelay:)
               withObject:block
               afterDelay:delay];
}

- (void)fireBlockAfterDelay:(void (^)(void))block {
    block();
}
@end

@implementation UIColor (HexStringToColor)
+(UIColor *)hexStringToColor:(NSString *)stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    
    if ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
    
}

+(UIColor *)skBackgroundColor{
    
    return [self hexStringToColor:@"#f2f2f2"];
}
+(UIColor *)skThemeColor{
    
    return [self hexStringToColor:@"#9E190E"];
}
@end

@implementation UIView (UIViewFrame)

- (CGFloat)left {
    return self.frame.origin.x;
}

- (void)setLeft:(CGFloat)x {
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

- (CGFloat)top {
    return self.frame.origin.y;
}

- (void)setTop:(CGFloat)y {
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

- (CGFloat)right {
    return self.frame.origin.x + self.frame.size.width;
}

- (CGFloat)bottom {
    return self.frame.origin.y + self.frame.size.height;
}

- (CGFloat)width {
    return self.frame.size.width;
}

- (void)setWidth:(CGFloat)width {
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (CGFloat)height {
    return self.frame.size.height;
}

- (void)setHeight:(CGFloat)height {
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}
@end


@implementation DOImageView
@synthesize imgURLStr;

-(void)dealloc
{
    imgURLStr=nil;
}

-(id)initWithFrame:(CGRect)frame
{
    
    self=[super initWithFrame:frame];
    if (self)
    {
        imgURLStr=nil;
        self.needCache=YES;
        self.defaultImg=@"ic_no_img_detail";
        self.actIndicatorColor=[UIColor blackColor];
    }
    return self;
    
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    for (UIView* view in [self subviews])
    {
        if ([view isMemberOfClass:[UIActivityIndicatorView class]])
        {
            view.frame=self.bounds;
            ((UIActivityIndicatorView*)view).color=self.actIndicatorColor;
            
        }
    }
}
+(BOOL)localExistFile:(NSString*)filename
{
    if([filename length])
    {
        NSArray * array=[filename pathComponents];
        return ([array count]==1);
    }
    return NO;
}

-(void)setImgData:(NSData *)imgData
{
    UIImage *image=[UIImage imageWithData:imgData];
    [self setImage:image];
}


-(void)setImgURLStr:(NSString *)strValue
{
    
    if(![strValue length])
    {
        imgURLStr=self.defaultImg;
    }
    else
    {
        imgURLStr=[strValue copy];
    }
    
    if (self.needCache&&strValue.length)
    {
        NSData *data = [DOImageView inquiryImageCache:strValue];
        if (data!=nil)
        {
            self.image = [UIImage imageWithData:data];
            if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(doImageViewLoad:img:)])
            {
                [self.delegate doImageViewLoad:self img:self.image];
            }
            return;
        }
    }
    
    if([DOImageView localExistFile:imgURLStr])
    {
        [self setImage:[UIImage imageNamed:imgURLStr]];
        if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(doImageViewLoad:img:)])
        {
            [self.delegate doImageViewLoad:self img:self.image];
        }
        return;
    }

    UIActivityIndicatorView* actIndicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    CGRect rect=self.bounds;
    actIndicator.frame=rect;
    
    actIndicator.color=self.actIndicatorColor;
    [actIndicator startAnimating];
    [self addSubview:actIndicator];
    
    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(  concurrentQueue,^{
        __block UIImage *image = nil;
        dispatch_sync( concurrentQueue,^{
            NSURL* url=[NSURL URLWithString:imgURLStr];
            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
            NSHTTPURLResponse *urlResponse = nil;
            NSError *downloadError = nil;
            NSData *imageData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&urlResponse error:&downloadError];
            if (downloadError == nil && imageData != nil && urlResponse.statusCode==200)
            {
                image=[UIImage imageWithData:imageData];
                if (self.needCache)
                {
                    [DOImageView savaImageData:imageData forUrl:strValue];
                }
            }
        });
        dispatch_sync(dispatch_get_main_queue(),^{
            
            [actIndicator stopAnimating];
            [actIndicator removeFromSuperview];
            
            if (image != nil)
            {
                [self setImage:image];
            }
            else
            {
                [self setImage:[UIImage imageNamed:self.defaultImg]];
            }
            if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(doImageViewLoad:img:)])
            {
                [self.delegate doImageViewLoad:self img:image];
            }
        });
        
    });
}



+(void)setImgUrl:(NSString *)strValue imgView:(UIImageView*)imgView
{

    NSData *data = [DOImageView inquiryImageCache:strValue];
    if (data!=nil)
    {
        [imgView setImage:[UIImage imageWithData:data]];
        return;
    }

    if([DOImageView localExistFile:strValue])
    {
        [imgView setImage:[UIImage imageNamed:strValue]];
        return;
    }

    UIActivityIndicatorView* actIndicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    CGRect rect=imgView.bounds;
    actIndicator.frame=rect;

    actIndicator.color=[UIColor darkGrayColor];
    [actIndicator startAnimating];
    [imgView addSubview:actIndicator];

    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(  concurrentQueue,^{
        __block UIImage *image = nil;
        dispatch_sync( concurrentQueue,^{
            NSURL* url=[NSURL URLWithString:strValue];
            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
            NSError *downloadError = nil;
            NSData *imageData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&downloadError];
            if (downloadError == nil && imageData != nil)
            {
                image=[UIImage imageWithData:imageData];
                [DOImageView savaImageData:imageData forUrl:strValue];
            }
        });
        dispatch_sync(dispatch_get_main_queue(),^{

            [actIndicator stopAnimating];
            [actIndicator removeFromSuperview];
            if (image != nil)
            {
                 [imgView setImage:image];
            }
        });

    });
}


//查询图片缓存
+ (NSData *)inquiryImageCache:(NSString *)imageUrl
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ImageCache" inManagedObjectContext:rootContext];
    [fetchRequest setEntity:entity];
    NSError *error;
    NSPredicate *Predicate = [NSPredicate predicateWithFormat:@"imageUrl = %@",imageUrl];
    [fetchRequest setPredicate:Predicate];
    NSArray *fetchedObjects = [rootContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects.count) {
        ImageCache *item = [fetchedObjects firstObject];
        return item.imageData;
    } else {
        return nil;
    }
}


//存储图片
+(void)savaImageData:(NSData *)imageData forUrl:(NSString *)imageUrl
{
    [netEngine.cdlock lock];
    ImageCache *item = [NSEntityDescription insertNewObjectForEntityForName:@"ImageCache" inManagedObjectContext:rootContext];
    item.imageUrl = imageUrl;
    item.imageData = imageData;
    NSError *error;
    if(![rootContext save:&error])
    {
        NSLog(@"%@",[error localizedDescription]);
    }
    [netEngine.cdlock unlock];
}

@end


@interface GXButton ()
{
    UILabel *_unreadLabel;
}
@end
@implementation GXButton
@synthesize object,numberCount;

-(void)setNumberCount:(int)count
{
    numberCount=count;
    [self layoutSubviews];
}

-(void)playCountAnimation
{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.3;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.3, 1.3, 1.3)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [_unreadLabel.layer addAnimation:animation forKey:nil];
}

- (void) layoutSubviews
{
    
    [super layoutSubviews];
    if (_unreadLabel==nil&& self.enableTip)
    {
        _unreadLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.width-11)/2.0,9, 16, 16)];
        _unreadLabel.backgroundColor = [UIColor redColor];
        _unreadLabel.textColor = [UIColor whiteColor];
        _unreadLabel.textAlignment = NSTextAlignmentCenter;
        _unreadLabel.font = [UIFont boldSystemFontOfSize:11];
        _unreadLabel.layer.cornerRadius = 8;
        _unreadLabel.clipsToBounds = YES;
        _unreadLabel.hidden=YES;
        [self addSubview:_unreadLabel];
    }
    
    if ( self.enableTip)
    {
        _unreadLabel.hidden=!self.numberCount;
        [self bringSubviewToFront:_unreadLabel];
        _unreadLabel.text = [NSString stringWithFormat:@"%d",self.numberCount];
    }
    
    if (_unreadLabel==nil&&self.showTip) {
        _unreadLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.width-5, 5, 5, 5)];
        _unreadLabel.backgroundColor = [UIColor hexStringToColor:@"#ff4400"];
        _unreadLabel.layer.cornerRadius = 2.5;
        _unreadLabel.clipsToBounds = YES;
        _unreadLabel.hidden = YES;
        [self addSubview:_unreadLabel];
    }
    
    if (self.showTip) {
        _unreadLabel.hidden=!self.numberCount;
        [self bringSubviewToFront:_unreadLabel];
    }
    
    if(self.relayout)
    {
        self.imageView.frame =self.imageViewFrame;
        self.titleLabel.frame=self.titleLabelFrame;
    }
}
-(void)dealloc
{
    object=nil;
}
@end


@implementation GXScrollToolBar
@synthesize dataArray,delegate,curSeletedBtn;

-(void)dealloc
{
    self.curSeletedBtn=nil;
    self.dataArray=nil;
    items=nil;
    _scrollContainer=nil;
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        items=[[NSMutableArray alloc]initWithCapacity:0];
        _scrollContainer=[[UIScrollView alloc]initWithFrame:self.bounds];
        _scrollContainer.bounces=NO;
        _scrollContainer.showsHorizontalScrollIndicator=NO;
        _scrollContainer.showsVerticalScrollIndicator=NO;
        _scrollContainer.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _scrollContainer.delegate=(id)self;
        _scrollContainer.backgroundColor=[UIColor clearColor];
        curSeletedBtn=nil;
        
        self.backgroundColor=[UIColor clearColor];
        self.bgImageView=[[DOImageView alloc] initWithFrame:self.bounds];
        [self insertSubview:self.bgImageView atIndex:0];
        [self addSubview:_scrollContainer];
    }
    return self;
}

-(GXButton*)getBtnIndex:(int)index
{
    return [items objectAtIndex:index];
}

-(void)TransferResponse:(GXButton*)sender;
{
    if(curSeletedBtn!=nil)
    {
        if(curSeletedBtn==sender && curSeletedBtn.selected)
        {
            [self.delegate scrollToolBarBtnRepeat];
            return;
        }
        curSeletedBtn.selected=NO;
    }
    self.curSeletedBtn=sender;
    curSeletedBtn.selected=YES;
    [self.delegate scrollToolBarBtnAction:sender toolBar:self];
    
}

-(void)setDefaultSelectedIndex:(int)index
{
    GXButton* sender=[items objectAtIndex:index];
    [self TransferResponse:sender];
}

-(void)initItems
{
    CGSize size=_scrollContainer.frame.size;
    int xpos=0;
    int count=(int)[dataArray count];
    
    //添加功能按钮
    for (int i=0;i< count; i++)
    {
    }
    [_scrollContainer setContentSize:CGSizeMake(xpos,size.height)];
}


-(void)setDataArray:(NSArray*)array
{
    dataArray=[array copy];
    [self initItems];
}

@end



@implementation SXProgressHUD
-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    for (UIView* item in [self subviews])
    {
        if ([item isMemberOfClass:[UIActivityIndicatorView class]])
        {
            item.center=self.center;
        }
    }
}

+(void) showHUDAddedTo:(UIView*)view animated:(BOOL)animated
{
    SXProgressHUD* hud=[[SXProgressHUD alloc]initWithFrame:view.bounds];
    hud.backgroundColor=[UIColor clearColor];
    [view addSubview:hud];
    
    UIActivityIndicatorView* actIndicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    actIndicator.frame=hud.bounds;
    UIColor* color=(view.backgroundColor==[UIColor blackColor])?[UIColor whiteColor]:[UIColor blackColor];
    actIndicator.color=color;
    [hud addSubview:actIndicator];
    [actIndicator startAnimating];
}

-(void)dealloc
{
    for (UIView* item in [self subviews])
    {
        [item removeFromSuperview];
    }
}

+(void) hideAllHUDsForView:(UIView*)view animated:(BOOL)animated
{
    for (UIView* item in [view subviews])
    {
        if ([item isMemberOfClass:[SXProgressHUD class]])
        {
            [item removeFromSuperview];
        }
    }
}

@end


@interface SXTextView ()
@property(nonatomic,strong)UILabel *placehoderLabel;
@end

@implementation SXTextView
@synthesize placehoder;


-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor=[UIColor clearColor];
        self.placehoderLabel=[[UILabel alloc]init];
        self.placehoderLabel.numberOfLines=0;
        self.placehoderLabel.frame=self.placehoderLabel.frame=CGRectMake(5, 5, self.width, 20);
        self.placehoderLabel.font=[UIFont systemFontOfSize:15];
        self.placehoderLabel.autoresizingMask=UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        self.placehoderLabel.backgroundColor=[UIColor clearColor];
        [self insertSubview:self.placehoderLabel atIndex:0];
        self.placehoderLabel.textColor=[UIColor lightGrayColor];
        self.font=[UIFont systemFontOfSize:15];
        self.scrollEnabled=YES;
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidBeginEditingNotification object:self];
        
        
    }
    return self;
}

-(void)dealloc
{
    self.placehoderLabel=nil;
    self.placehoder=nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(void)textDidChange
{
    self.placehoderLabel.hidden=(self.text.length!=0);
    
    self.placehoderLabel.frame=CGRectMake(5, 5, self.width, 20);
}

-(void)setPlacehoder:(NSString *)strValue
{
    placehoder=[strValue copy];
    self.placehoderLabel.text=placehoder;
}

@end


@implementation SXNavigation
static SXNavigation* navgation;

-(void)dealloc
{
    rootViewCtr=nil;
    viewStack=nil;
}

+(SXNavigation*)shareNavigation
{
    @synchronized(self)
    {
        if(navgation==nil)
        {
            navgation=[[SXNavigation alloc]init];
        }
    }
    return navgation;
}

-(BOOL)isToRootViewController
{
    return (index==0);
}

+(id)allocWithZone:(struct _NSZone *)zone
{
    @synchronized(self)
    {
        if (navgation==nil )
        {
            navgation=[super allocWithZone:zone];
            return navgation;
        }
    }
    return nil;
}

-(void)initWithRootViewController:(UIViewController*)_viewCtr
{
    viewStack=nil;
    viewStack=[[NSMutableArray alloc]initWithCapacity:0];
    rootViewCtr=nil;
    rootViewCtr=_viewCtr;
    index=0;
    [viewStack insertObject:rootViewCtr atIndex:index];
}

- (void)pushViewController:(UIViewController*)_viewCtr animated:(BOOL)animated
{
    UIViewController* disappearVctr=[viewStack objectAtIndex:index];
    [disappearVctr viewWillDisappear:animated];
    
    index++;
    [viewStack insertObject:_viewCtr atIndex:index];
    
    CGRect rect=_viewCtr.view.frame;
    CGPoint point= CGPointMake(rect.origin.x+rect.size.width, rect.origin.y);
    rect.origin=point;
    _viewCtr.view.frame=rect;
    [rootViewCtr.view addSubview:_viewCtr.view];
    
    if (animated)
    {
        CGContextRef context=UIGraphicsGetCurrentContext();
        [UIView beginAnimations:nil context:context];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:0.3];
        point= CGPointMake(0, rect.origin.y);
        rect.origin=point;
        _viewCtr.view.frame=rect;
        [UIView commitAnimations];
    }
    else
    {
        point= CGPointMake(0, rect.origin.y);
        rect.origin=point;
        _viewCtr.view.frame=rect;
    }
    [_viewCtr viewWillAppear:animated];
}

-(void)removeTopView:(UIViewController*)_viewCtr
{
    [_viewCtr.view removeFromSuperview];
}

-(void)clearData
{
    viewStack=nil;
    index=0;
}

- (void)popToRootViewControllerAnimated:(BOOL)animated
{
    if(index==0)
        return;
    
    UIViewController* _viewCtr=[viewStack objectAtIndex:index];
    [_viewCtr viewWillDisappear:animated];
    
    CGRect rect=_viewCtr.view.frame;
    CGPoint point= CGPointMake(rect.origin.x+rect.size.width, rect.origin.y);
    rect.origin=point;
    
    CATransition* animation=[CATransition animation];
    [animation setType:kCATransitionPush];
    [animation setSubtype:kCATransitionFromLeft];
    [animation setDuration:0.3f];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    _viewCtr.view.frame=rect;
    [_viewCtr.view.layer addAnimation:animation forKey:nil];
    [viewStack removeObjectAtIndex:index];
    
    for (index-=1;index>0;index--)
    {
        UIViewController* Vctr=[viewStack objectAtIndex:index];
        [Vctr.view removeFromSuperview];
        [viewStack removeObjectAtIndex:index];
    }
    
    [self performBlock:
     ^{
         [_viewCtr.view removeFromSuperview];
     } afterDelay:0.5f];
    
    UIViewController* appearVctr=[viewStack objectAtIndex:0];
    [appearVctr viewWillAppear:animated];
}

- (void)popViewControllerAnimated:(BOOL)animated
{
    if(index==0)
        return;
    
    UIViewController* _viewCtr=[viewStack objectAtIndex:index];
    
    CGRect rect=_viewCtr.view.frame;
    CGPoint point= CGPointMake(rect.origin.x+rect.size.width, rect.origin.y);
    rect.origin=point;
    
    if (animated)
    {
        CATransition* animation=[CATransition animation];
        [animation setType:kCATransitionPush];
        [animation setSubtype:kCATransitionFromLeft];
        [animation setDuration:0.3f];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
        _viewCtr.view.frame=rect;
        [_viewCtr.view.layer addAnimation:animation forKey:nil];
    }
    else
    {
        _viewCtr.view.frame=rect;
    }
    [_viewCtr viewWillDisappear:animated];
    
    [self performSelector:@selector(removeTopView:) withObject:_viewCtr afterDelay:0.5f];
    [viewStack removeObjectAtIndex:index];
    index--;
    UIViewController* appearVctr=[viewStack objectAtIndex:index];
    [appearVctr viewWillAppear:animated];
    
}
@end


@implementation GXLevelControl
@synthesize levelNum,levelTotal;
-(void)setLevelNum:(int)num
{
    levelNum=num;
    
    if (self.selectedImgUrl==nil)
    {
        self.selectedImgUrl=@"btn_star_pre";
    }
    for (int i=0; i<levelNum; i++)
    {
        UIImageView* imgView=[items objectAtIndex:i];
        [imgView setImage:[UIImage imageNamed: self.selectedImgUrl]];
    }
}

-(void)setLevelTotal:(int)num
{
    levelTotal=num;
    CGRect rect=self.bounds;
    float x=0;
    items=[[NSMutableArray alloc]initWithCapacity:0];
    
    if (self.normalImgUrl==nil)
    {
        self.normalImgUrl=@"btn_star_nor";
    }
    
    for (int i=0; i<levelTotal; i++)
    {
        CGRect rc=CGRectMake(x, 0, (rect.size.width-2.0)/levelTotal, rect.size.height);
        UIImageView* imgView=[[UIImageView alloc]initWithFrame: rc];
        [imgView setImage:[UIImage imageNamed:self.normalImgUrl]];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        
        [ self addSubview:imgView];
        [items insertObject:imgView atIndex:i];
        
        x+=(rect.size.width/levelTotal+0.5);
    }
    
}
@end





@implementation DOMarkView
@synthesize selected;

-(id)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if (self)
    {
        self.showLine=YES;
        [self initUI];
    }
    return self;
}

-(void)initUI
{
    int x=15,y=10;
    CGRect rect=CGRectMake(x, y,self.width-2*x, 20);
    UILabel* titleLabel=[[UILabel alloc] initWithFrame:rect];
    titleLabel.tag=101;
    titleLabel.font=[UIFont systemFontOfSize:14];
    [self addSubview:titleLabel];
}

-(void)setTitle:(NSString *)title
{
    _title=title;
    UILabel* titleLabel=(UILabel*)[self viewWithTag:101];
    [titleLabel setText:title];
}

-(void)setSelected:(NSString *)value
{
    selected=value;
    if (value!=nil)
    {
        NSArray* selectedItems=[value componentsSeparatedByString:@"/"];
        for (NSString* item in selectedItems)
        {
            for (int i=0; i<self.marks.count; i++)
            {
                UIButton* btn=(UIButton*)[self viewWithTag:(200+i)];
                if ([btn.titleLabel.text isEqualToString:item])
                {
                    btn.selected=YES;
                    if (self.isSingle)
                    {
                        self.curBtn=btn;
                    }
                    btn.layer.borderColor=KGreenColor.CGColor;
                    btn.backgroundColor=KGreenColor;
                }
            }
            
        }
    }
    else
    {
        [self cleanSelected];
    }
}

-(void)setMarks:(NSArray *)marks
{
    _marks=marks;
    for (int i=0; i<marks.count; i++)
    {
        NSString* strText=marks[i];
        UIFont* font=[UIFont systemFontOfSize:13];
        float width=[HDUtil sizeWithString:strText font:font size:CGSizeMake(MAXFLOAT, 28)].width;
        width+=20;
        CGRect rect=CGRectMake(0, 0, width, 28);
        UIButton* btn=[[UIButton alloc] initWithFrame:rect];
        btn.tag=200+i;
        btn.layer.cornerRadius=3;
        btn.layer.borderWidth=0.5;
        btn.layer.borderColor=[UIColor lightGrayColor].CGColor;
        btn.titleLabel.font=font;
        [btn setTitle:strText forState:UIControlStateNormal];
        [btn setTitle:strText forState:UIControlStateSelected];
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
    }
    
    if(self.showLine)
    {
        DOImageView* sepLine=[[DOImageView alloc]initWithFrame:CGRectMake(15,0, self.width-30, 0.5)];
        sepLine.imgURLStr=@"dot";
        sepLine.tag=102;
        [self addSubview:sepLine];
    }
    [self resetlayout];
}

-(void)resetlayout
{
    float offsetX=15,offsetY=35;
    float widthMax=self.width-15;
    for (int i=0; i<self.marks.count; i++)
    {
        UIView* btn=[self viewWithTag:200+i];
        if ((offsetX+btn.width)>widthMax)
        {
            offsetX=15;
            offsetY+=(btn.height+10);
        }
        btn.left=offsetX;
        btn.top=offsetY;
        offsetX+=(btn.width+10);
    }
    
    self.height=(offsetY+38);
    UIView* line=[self viewWithTag:102];
    if (line!=nil)
    {
        line.top=self.height-0.5;
    }
    
}

-(void)cleanSelected
{
    for (int i=0; i<self.marks.count; i++)
    {
        UIButton* btn=(UIButton*)[self viewWithTag:(200+i)];
        btn.selected=NO;
        btn.backgroundColor=[UIColor whiteColor];
        btn.layer.borderColor=[UIColor lightGrayColor].CGColor;
    }
    self.curBtn=nil;
    selected=nil;
}

-(void)btnAction:(UIButton*)sender
{
    [HDUtil hidenKeyBoard];
    if (self.isSingle)
    {
        if (self.curBtn!=sender)
        {
            self.curBtn.selected=NO;
            self.curBtn.layer.borderColor=[UIColor lightGrayColor].CGColor;
            self.curBtn.backgroundColor=[UIColor whiteColor];
            self.curBtn=sender;
        }
    }
    
    sender.selected=!sender.selected;
    if (sender.selected)
    {
        sender.backgroundColor=KGreenColor;
        sender.layer.borderColor=KGreenColor.CGColor;
    }
    else
    {
        sender.layer.borderColor=[UIColor lightGrayColor].CGColor;
        sender.backgroundColor=[UIColor whiteColor];
    }
}

-(NSString*)selected
{
    NSString* str=nil;
    
    for (int i=0; i<self.marks.count; i++)
    {
        UIButton* btn=(UIButton*)[self viewWithTag:(200+i)];
        if (btn.selected)
        {
            if (str==nil)
            {
                str=[NSString string];
            }
            else
            {
                str=[str stringByAppendingString:@"/"];
            }
            
            str=[str stringByAppendingString:btn.titleLabel.text];
        }
    }
    return str;
}
@end





@interface HDAccountInput ()
@property UILabel*  valueLabel;
@property GXButton* reduceBtn;
@property GXButton* addBtn;
@end

@implementation HDAccountInput
@synthesize reduceBtn,addBtn,valueLabel;

-(id)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if (self)
    {
        float y=(self.height-30)/2.0;
        reduceBtn=[GXButton buttonWithType:UIButtonTypeCustom];
        reduceBtn.frame=CGRectMake(0,y, 30, 30);
        reduceBtn.relayout=YES;
        reduceBtn.imageViewFrame=CGRectMake(7, 7, 16, 16);
        reduceBtn.layer.borderColor=[UIColor lightGrayColor].CGColor;
        reduceBtn.layer.borderWidth=0.5;
        reduceBtn.backgroundColor=[UIColor whiteColor];
        [reduceBtn setImage:[UIImage imageNamed:@"reduceBtn"] forState:UIControlStateNormal];
        [reduceBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:reduceBtn];
        
        valueLabel=[[UILabel alloc] initWithFrame:CGRectMake(reduceBtn.right-1,y,50, 30)];
        valueLabel.font=[UIFont systemFontOfSize:16];
        valueLabel.textAlignment=NSTextAlignmentCenter;
        valueLabel.backgroundColor=[UIColor whiteColor];
        valueLabel.layer.borderColor=[UIColor lightGrayColor].CGColor;
        valueLabel.layer.borderWidth=0.5;
        [self insertSubview:valueLabel belowSubview:reduceBtn];
        
        addBtn=[GXButton buttonWithType:UIButtonTypeCustom];
        addBtn.frame=CGRectMake(valueLabel.right-1,y, 30, 30);
        addBtn.relayout=YES;
        addBtn.imageViewFrame=CGRectMake(7, 7, 16, 16);
        addBtn.layer.borderColor=[UIColor lightGrayColor].CGColor;
        addBtn.layer.borderWidth=0.5;
        addBtn.backgroundColor=[UIColor whiteColor];
        [addBtn setImage:[UIImage imageNamed:@"inCreaseBtn"] forState:UIControlStateNormal];
        [addBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:addBtn];
        
    }
    return self;
}

-(void)setValue:(int)value
{
    _value=(value>1)?value:1;
    valueLabel.text=[NSString stringWithFormat:@"%d",_value];
}


-(void)btnAction:(GXButton*)sender
{
    if (sender==reduceBtn)
    {
        self.value--;
    }
    else
    {
       self.value++;
    }
}

@end

@implementation HDTextField

- (id)initWithFrame:(CGRect)frame icon:(NSString *)icon title:(NSString *)title
{
    self = [super initWithFrame:frame];
    if (self) {
        self.leftViewMode = UITextFieldViewModeAlways;
        GXButton *leftView = [GXButton buttonWithType:UIButtonTypeCustom];
        float width = 40;
        if (icon.length&&title.length) {
            width = 80;
        }
        leftView.imageView.contentMode = UIViewContentModeScaleAspectFit;
        leftView.frame = CGRectMake(0, 0, width, 40);
        if (icon.length&&!title.length) {
            leftView.imageViewFrame = CGRectMake(12, 12, 15, 16);
        } else if (icon.length&&title.length) {
            leftView.imageViewFrame = CGRectMake(5, 12, 15, 16);
            leftView.titleLabelFrame = CGRectMake(30, 0, 50, 40);
        }
        leftView.relayout = YES;
        [leftView setImage:[UIImage imageNamed:icon] forState:UIControlStateNormal];
        [leftView setTitle:title forState:UIControlStateNormal];
        [leftView setTitleColor:kDarkGrayColor forState:UIControlStateNormal];
        leftView.titleLabel.font = [UIFont systemFontOfSize:15];
        self.leftView = leftView;
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame isRightAngle:(BOOL)isRightAngle
{
    self = [super initWithFrame:frame];
    if (self) {
        if (isRightAngle) {
            self.layer.borderColor = [UIColor colorWithRed:0.8235 green:0.8235 blue:0.8314 alpha:1].CGColor;
            self.layer.borderWidth = 0.5;
            self.font = [UIFont systemFontOfSize:15];
        }
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, self.height)];
        self.leftViewMode = UITextFieldViewModeAlways;
        self.leftView = leftView;
    }
    return self;
}

@end

@interface HDDatePickerView ()
@property(nonatomic,strong)UIView *coverView;
@property(nonatomic,strong)UIView *contentView;
@property(nonatomic,strong)UIButton *finishBtn;
@property(nonatomic,strong)CDatePickerViewEx *datePicker;
@end
@implementation HDDatePickerView

- (void)show
{
    UIWindow *window = [UIApplication sharedApplication].windows[0];
    if (!self.coverView.superview) {
        self.contentView.top = SCREENFRAME.size.height;
        [window addSubview:self.coverView];
        [UIView animateWithDuration:0.3 animations:^{
            self.contentView.top = SCREENFRAME.size.height-self.height;
        }];
    }
}

- (void)dismiss
{
    [self.coverView removeFromSuperview];
}

- (void)finish:(UIButton *)sender
{
    [self dismiss];
    if ([self.delegate respondsToSelector:@selector(datePickerPickDone:)]) {
        [self.delegate datePickerPickDone:self.datePicker.date];
    }
}

- (UIView *)coverView
{
    if (!_coverView) {
        _coverView = [[UIView alloc] initWithFrame:SCREENFRAME];
        _coverView.backgroundColor = kCoverColor;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
        [_coverView addGestureRecognizer:tapGesture];
    }
    return _coverView;
}

- (UIView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREENFRAME.size.height, self.width, self.height)];
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.alpha = 0.9;
        [self.coverView addSubview:_contentView];
        [_contentView addSubview:self.datePicker];
        [_contentView addSubview:self.finishBtn];
    }
    return _contentView;
}

- (CDatePickerViewEx *)datePicker
{
    if (!_datePicker) {
        _datePicker = [[CDatePickerViewEx alloc] initWithFrame:CGRectMake(0, 30, self.width, self.height-30)];
    }
    return _datePicker;
}

- (UIButton *)finishBtn
{
    if (!_finishBtn) {
        _finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _finishBtn.frame = CGRectMake(self.width-50, 0, 40, 30);
        [_finishBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_finishBtn setTitleColor:[UIColor hexStringToColor:@"#e94929"] forState:UIControlStateNormal];
        _finishBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_finishBtn addTarget:self action:@selector(finish:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _finishBtn;
}

@end

@interface HDTipView()
@end
@implementation HDTipView

+(void)showTipWithMsg:(NSString*)msg imgIcon:(NSString*)iconUrl hudView:(UIView*)hudView
{
    HDTipView* tipView=[[HDTipView alloc] init];
    tipView.backgroundColor=[UIColor colorWithRed:0.8824 green:0.8863 blue:0.8902 alpha:1];
    tipView.layer.cornerRadius=10;
    
    CGRect rect=hudView.frame;
    CGSize size=[HDUtil sizeWithString:msg font:[UIFont systemFontOfSize:15] size:CGSizeMake(rect.size.width-80, CGFLOAT_MAX)];
    UILabel* tipLabel=[HDUtil UILabelWithText:msg fontSize:15];
    tipLabel.textAlignment=NSTextAlignmentCenter;
    tipLabel.numberOfLines=0;
    tipLabel.textColor=kDarkGrayColor;
    
    for (UIView *item in [hudView subviews]) {
        if ([item isMemberOfClass:[HDTipView class]]) {
            [item removeFromSuperview];
        }
    }
    
    [tipView addSubview:tipLabel];
    
    if (iconUrl!=nil && iconUrl.length)
    {
        tipView.frame=CGRectMake(0,0,size.width+40, size.height+96);
        if (tipView.width<120) {
            tipView.width = 120;
        }
        DOImageView* iconImgView=[[DOImageView alloc] initWithFrame:CGRectMake((tipView.width-56)/2.0, 20, 56, 56)];
        iconImgView.imgURLStr=iconUrl;
        [tipView addSubview:iconImgView];
        
        tipLabel.frame=CGRectMake(0,86,tipView.width,size.height);
    }
    else
    {
        tipView.frame=CGRectMake(0,0,size.width+40, size.height+40);
        tipLabel.frame=CGRectMake(0,20,tipView.width,size.height);
    }
    
    tipView.center=CGPointMake(hudView.frame.size.width/2.0, hudView.frame.size.height/2.0);
    [hudView addSubview:tipView];
    [hudView performBlock:^
     {
         [tipView removeFromSuperview];
         
     }afterDelay:1.5];
}

@end
// Identifiers of components
#define MONTH ( 1 )
#define YEAR ( 0 )

// Identifies for component views
#define LABEL_TAG 43


@interface CDatePickerViewEx()

@property (nonatomic, strong) NSIndexPath *todayIndexPath;
@property (nonatomic, strong) NSArray *months;
@property (nonatomic, strong) NSArray *years;

-(NSArray *)nameOfYears;
-(NSArray *)nameOfMonths;
-(CGFloat)componentWidth;

-(UILabel *)labelForComponent:(NSInteger)component selected:(BOOL)selected;
-(NSString *)titleForRow:(NSInteger)row forComponent:(NSInteger)component;
-(NSIndexPath *)todayPath;
-(NSInteger)bigRowMonthCount;
-(NSInteger)bigRowYearCount;
-(NSString *)currentMonthName;
-(NSString *)currentYearName;

@end

@implementation CDatePickerViewEx

const NSInteger bigRowCount = 1000;
const NSInteger minYear = 2008;
const NSInteger maxYear = 2030;
const CGFloat rowHeight = 44.f;
const NSInteger numberOfComponents = 2;

@synthesize todayIndexPath;
@synthesize months;
@synthesize years = _years;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.months = [self nameOfMonths];
        self.years = [self nameOfYears];
        self.todayIndexPath = [self todayPath];
        
        self.delegate = self;
        self.dataSource = self;
        
        [self selectToday];
    }
    return self;
}

-(NSDate *)date
{
    NSInteger monthCount = [self.months count];
    NSString *month = [self.months objectAtIndex:([self selectedRowInComponent:MONTH] % monthCount)];
    
    NSInteger yearCount = [self.years count];
    NSString *year = [self.years objectAtIndex:([self selectedRowInComponent:YEAR] % yearCount)];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMMM:yyyy"];
    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%@:%@", month, year]];
    return date;
}

#pragma mark - UIPickerViewDelegate
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return [self componentWidth];
}

-(UIView *)pickerView: (UIPickerView *)pickerView
           viewForRow: (NSInteger)row
         forComponent: (NSInteger)component
          reusingView: (UIView *)view
{
    BOOL selected = NO;
    if(component == MONTH)
    {
        NSInteger monthCount = [self.months count];
        NSString *monthName = [self.months objectAtIndex:(row % monthCount)];
        NSString *currentMonthName = [self currentMonthName];
        if([monthName isEqualToString:currentMonthName] == YES)
        {
            selected = YES;
        }
    }
    else
    {
        NSInteger yearCount = [self.years count];
        NSString *yearName = [self.years objectAtIndex:(row % yearCount)];
        NSString *currenrYearName  = [self currentYearName];
        if([yearName isEqualToString:currenrYearName] == YES)
        {
            selected = YES;
        }
    }
    
    UILabel *returnView = nil;
    if(view.tag == LABEL_TAG)
    {
        returnView = (UILabel *)view;
    }
    else
    {
        returnView = [self labelForComponent: component selected: selected];
    }
    
    returnView.textColor = selected ? [UIColor blueColor] : [UIColor blackColor];
    returnView.text = [self titleForRow:row forComponent:component];
    return returnView;
}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return rowHeight;
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return numberOfComponents;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(component == MONTH)
    {
        return [self bigRowMonthCount];
    }
    return [self bigRowYearCount];
}

#pragma mark - Util
-(NSInteger)bigRowMonthCount
{
    return [self.months count]  * bigRowCount;
}

-(NSInteger)bigRowYearCount
{
    return [self.years count]  * bigRowCount;
}

-(CGFloat)componentWidth
{
    return self.bounds.size.width / numberOfComponents;
}

-(NSString *)titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(component == MONTH)
    {
        NSInteger monthCount = [self.months count];
        return [self.months objectAtIndex:(row % monthCount)];
    }
    NSInteger yearCount = [self.years count];
    return [self.years objectAtIndex:(row % yearCount)];
}

-(UILabel *)labelForComponent:(NSInteger)component selected:(BOOL)selected
{
    CGRect frame = CGRectMake(0.f, 0.f, [self componentWidth],rowHeight);
    
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    label.textColor = selected ? [UIColor blueColor] : [UIColor blackColor];
    label.font = [UIFont boldSystemFontOfSize:18.f];
    label.userInteractionEnabled = NO;
    
    label.tag = LABEL_TAG;
    
    return label;
}

-(NSArray *)nameOfMonths
{
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    return [dateFormatter standaloneMonthSymbols];
}

-(NSArray *)nameOfYears
{
    NSMutableArray *years = [NSMutableArray array];
    
    for(NSInteger year = minYear; year <= maxYear; year++)
    {
        NSString *yearStr = [NSString stringWithFormat:@"%li", (long)year];
        [years addObject:yearStr];
    }
    return years;
}

-(void)selectToday
{
    [self selectRow: self.todayIndexPath.row
        inComponent: MONTH
           animated: NO];
    
    [self selectRow: self.todayIndexPath.section
        inComponent: YEAR
           animated: NO];
}

-(NSIndexPath *)todayPath // row - month ; section - year
{
    CGFloat row = 0.f;
    CGFloat section = 0.f;
    
    NSString *month = [self currentMonthName];
    NSString *year  = [self currentYearName];
    
    //set table on the middle
    for(NSString *cellMonth in self.months)
    {
        if([cellMonth isEqualToString:month])
        {
            row = [self.months indexOfObject:cellMonth];
            row = row + [self bigRowMonthCount] / 2;
            break;
        }
    }
    
    for(NSString *cellYear in self.years)
    {
        if([cellYear isEqualToString:year])
        {
            section = [self.years indexOfObject:cellYear];
            section = section + [self bigRowYearCount] / 2;
            break;
        }
    }
    
    return [NSIndexPath indexPathForRow:row inSection:section];
}

-(NSString *)currentMonthName
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMMM"];
    return [formatter stringFromDate:[NSDate date]];
}

-(NSString *)currentYearName
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy"];
    return [formatter stringFromDate:[NSDate date]];
}

@end






























